/*
 * @Author: 烟浮
 * @Date: 2022-06-26 01:29:47
 * @LastEditTime: 2022-06-26 03:01:31
 * @LastEditors: 锦墨涵秋 275740441@qq.com
 * @FilePath: /vite-ts-vue3/src/store/cart.ts
 */
import { defineStore } from 'pinia';
import { useProductsStore } from '../store/products';
import { IProduct, buyProducts } from '../api/shop';

type CartProduct = {
    quantity: number
} & Omit<IProduct, 'inventory'> // Omit 过滤掉 IProduct 中的 inventory

export const useCartStore = defineStore('cart', {
    state: () => {
        return {
            cartProducts: [] as CartProduct[],
            checkoutStatus: null as null | string
        }
    },
    getters: {
        totalPrice(state) {
            return state.cartProducts.reduce((total, item) => {
                return total + item.price * item.quantity
            }, 0)
        }
    },
    actions: {
        addProductToCart(product: IProduct) {
            // 看商品有没有库存
            if (product.inventory < 1) {
                return
            }
            // 检查购物车是否有该商品
            const cartItem = this.cartProducts.find(item => item.id === product.id)
            if (cartItem) {
                // 如果购物车有商品则让数量 + 1
                cartItem.quantity++
            } else {
                // 如果没有，则添加到购物车列表中
                this.cartProducts.push({
                    id: product.id,
                    title: product.title,
                    price: product.price,
                    quantity: 1
                })
            }
            // 更新商品的库存
            const productsStore = useProductsStore()
            productsStore.decrementProduct(product)

        },
        async checkouts() {
            const ret = await buyProducts()
            this.checkoutStatus = ret ? '成功' : '失败'
            if (ret) {
                this.cartProducts = []
            }
        }
    }
})